package com.gitee.qdbp.jdbc.tags;

import java.io.IOException;
import com.gitee.qdbp.jdbc.api.SqlBoot;
import com.gitee.qdbp.jdbc.sql.SqlBuffer;
import com.gitee.qdbp.jdbc.sql.parse.SqlCachingWriter;
import com.gitee.qdbp.staticize.common.IWriter;
import com.gitee.qdbp.staticize.exception.TagException;
import com.gitee.qdbp.staticize.tags.base.BaseEachTag;

/**
 * 输出SQL的Each标签
 *
 * @author zhaohuihua
 * @version 20210427
 */
public class SqlCachingEachTag extends BaseEachTag<SqlCachingWriter> {

    public SqlCachingEachTag(SqlBoot sqlBoot) {
        super(new SqlCachingWriter(sqlBoot.sqlDialect(), sqlBoot.plugins()));
    }

    @Override
    protected final void doEnded(SqlCachingWriter caching, IWriter origin) throws TagException, IOException {
        doEnded(caching.getContent(), origin);
        caching.clear();
    }

    protected void doEnded(SqlBuffer buffer, IWriter writer) throws TagException, IOException {
        if (buffer.isBlank()) {
            return;
        }

        // 循环标签不需要输出前置空白, 因为迭代内容已经有换行符了

        if (this.isInline() && !this.es.isFirst()) {
            writer.write(buffer.trimLeft());
        } else {
            writer.write(buffer);
        }
    }
}
